// author: shelman
// description：封装了Websocket服务示例的接口
#pragma once

#include <string>
#include <functional>
#include <vector>
#include <mutex>

//#define USE_WEBSOCKET 1
//#define USE_SSL = 1
#include "civetweb/civetweb.h"
#include "civetweb/CivetServer.h"

#include "export_def.h"

struct mg_connection;


// 定义Websocket基础类
class API_EXPORT_DECL WebsocketBaseHandler : public CivetWebSocketHandler
{
public:
    WebsocketBaseHandler() = default;
    virtual ~WebsocketBaseHandler() override;

    void setUrl(std::string strUrl);
    std::string getUrl() const;
    void setPfnCBDealData(std::function<void(const std::string &, void *, void *)> pfnCBDealData, void *pContext);
    virtual size_t getConnectionSize();

    virtual bool handleConnection(CivetServer *server, const struct mg_connection *conn) override;
    virtual void handleClose(CivetServer *server, const struct mg_connection *conn) override;
    virtual bool handleData(CivetServer *server, struct mg_connection *conn, int bits, char *data, size_t data_len) override;

    virtual void sendData(const char *pData, size_t iDataLen);
    virtual void sendData(const char *pData, size_t iDataLen, void *pConn);
    virtual void sendData(const std::string &strData);
    virtual void sendData(const std::string &strData, void *pConn);

protected:
    std::string m_strUrl = "";
    void *m_pContext = nullptr;
    std::mutex m_mt4Conns;
    std::vector<const struct mg_connection *> m_vt4Conns;

    // param1：回调的数据
    // param2：调用的上下文
    // param3：通信句柄
    std::function<void(const std::string &, void *, void *)> m_pfnCBDealData = nullptr;
};

// 示例XXX的类
class API_EXPORT_DECL Example1WebsocketHandler : public WebsocketBaseHandler
{
public:
    Example1WebsocketHandler();
    virtual ~Example1WebsocketHandler();
};

// 示例XXX的类
class API_EXPORT_DECL Example2WebsocketHandler : public WebsocketBaseHandler
{
public:
    Example2WebsocketHandler();
    virtual ~Example2WebsocketHandler();
};
